/**
 * 小程序消息订阅功能模块
 */

import Api from '@/api/api-declare';
import PD from '.';
/**
 * @param {Array} tmplIds 本次要订阅的消息的数组集合
 * @param {Number} type 2-司机  3-车队
 * -无论内部逻辑如何，最终都resolve，确保不对后续业务产生影响
 */
export function requestSubscribeMessage(tmplIds): Promise<void> {
	return new Promise(async (r) => {
		if (!Array.isArray(tmplIds) || !tmplIds.length) {
			console.error('msg-subscribe.js -> 参数异常');
			return;
		}
		try {
			const hasPermission = await hasMsgPermission();
			if (!hasPermission) {//没有消息权限，直接返回Promise.reject
				r();
				return;
			};

			const regTmplIds = await getNeedRegTmplIds(tmplIds);
			//如果没有需要注册的消息，直接退出
			if (!regTmplIds.length) {
				r();
				return;
			};

			uni.requestSubscribeMessage({
				tmplIds: regTmplIds,
				success: res => {
					const acceptMsgIds = tmplIds.filter(v => res[v] === 'accept');
					if (acceptMsgIds.length) {//有需要注册的消息，就向服务端进行注册
						regMsgIds2server(acceptMsgIds);
					};
				},
				complete: () => {
					r();
				}
			});

		} catch (e) {
			//TODO handle the exception
			r();
		};
	});
}


export function regMsgIds2server(templates: string[]): Promise<void> {
	return new Promise((r) => {
		Api.ApiCommon.miniMsgRegister({
			template_ids: templates,
			showErrorModal: false
		}).then(() => {
			r();
		}).catch(() => {
			r();
		});
	});
}

/**
 * @param {Object} tmplIds
 * @returns {Promise<string[]>} 需要完成向服务端注册的模板消息id
 */
export function getNeedRegTmplIds(tmplIds): Promise<string[]> {
	return new Promise((r) => {
		Api.ApiCommon.miniMsgCheck({
			showErrorModal: false,
			template_ids: tmplIds,
		}).then(res => {
			const v = res.filter(v => v.used);
			r(v && v.length ? v.map(t => t.template_id) : []);
		}).catch(() => {
			r([]);
		});
	});
}

/**
 * 是否打开了订阅消息开关
 */
export function hasMsgPermission(): Promise<boolean> {
	return new Promise((r) => {
		PD.UniHelp.getSetting(true).then(res => {
			r(Boolean(res.subscriptionsSetting.mainSwitch));
		}).catch(() => {
			r(false);
		});
	});
}